<template>
  <a-card :bodyStyle="{ padding: 0 }">
    <div class="p-15">
      <a-row>
        <a-col :span="12"><span>任务管理</span></a-col>
        <a-col :span="12">
          <a-space :size="15" class="float-right">
            <a-select allowClear v-model:value="table.search.vm.projectId" show-search placeholder="选择项目" style="width: 200px" :filter-option="filterOption" @change="handleChange">
              <a-select-option v-for="item in projectSource" v-bind:key="item.id">{{ item.name }}</a-select-option>
            </a-select>
            <a-button type="primary" @click="run()">运行</a-button>
            <a-button type="danger" @click="close()">关闭</a-button>
            <a-button type="primary" @click="openForm()" class="float-right"> <PlusCircleOutlined />新建 </a-button>
            <a-button type="primary" @click="findList()" class="float-right"> <RedoOutlined />刷新 </a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>
    <div>
      <a-table
        :customRow="onClickRow"
        :row-selection="{
          selectedRowKeys: table.selectedRowKeys,
          onChange: onSelectChange,
        }"
        :custom-row="customRow"
        :data-source="dataSource"
        :columns="columns"
        bordered
        :loading="table.loading"
        :rowKey="(record) => record.id"
        :pagination="false"
        size="small"
        :scroll="{ y: 'calc(100vh - 250px)', x: 'calc(100vw - 150px)' }"
      >
        <template #time="{ text: time }">
          {{ time ? timeFormat(time) : "" }}
        </template>
        <template #state="{ text: state }">
          <span>
            <a-tag :key="state" :color="state === 1 ? 'success' : 'error'">
              {{ state === 0 ? "已关闭" : "运行中" }}
            </a-tag>
          </span>
        </template>
        <template #requsetMode="{ text: requsetMode }">
          <span>
            <a-tag :key="requsetMode" :color="requsetMode === 0 ? 'orange' : requsetMode === 1 ? 'cyan' : 'purple'">
              {{ requsetMode === 0 ? "Post" : requsetMode === 1 ? "Get" : "Delete" }}
            </a-tag>
          </span>
        </template>
        <template #action="{ record }">
          <a-dropdown v-model:visible="record.visible">
            <a class="ant-dropdown-link" @click.prevent>
              操作
              <DownOutlined />
            </a>
            <template #overlay>
              <a-menu>
                <a-menu-item key="1" @click="openForm(record.id)"> 修改 </a-menu-item>
                <a-menu-item key="2" @click="deleteList(record.id)" class="text-danger"> 删除 </a-menu-item>
                <a-menu-item key="3" @click="openRecord(record.id)"> 日志 </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </a-table>
    </div>
  </a-card>
  <!--弹层-->
  <a-drawer title="执行记录" placement="right" :closable="false" v-model:visible="form.revisible" :width="1200" destroyOnClose>
    <record v-model:formId="form.key" />
  </a-drawer>

  <a-modal v-model:visible="form.visible" title="编辑" centered :width="800" :footer="null" destroyOnClose>
    <info v-model:formId="form.key" @onSaveSuccess="saveChange" />
  </a-modal>
  <!-- <a-modal v-model:visible="form.revisible" title="执行记录" centered :width="1200" :footer="null" :height="800" destroyOnClose>
    <record v-model:formId="form.key" />
  </a-modal> -->
</template>
<script>
import { defineComponent, onMounted, reactive, toRefs, onBeforeUnmount } from "vue";
import { PlusCircleOutlined, RedoOutlined, DownOutlined } from "@ant-design/icons-vue";
import info from "./info";
import record from "./record";
import service from "@/services/service";
import tools from "@/services/tools";
import moment from "moment";

export default defineComponent({
  components: {
    PlusCircleOutlined,
    RedoOutlined,
    info,
    record,
    DownOutlined,
  },
  name: "Task",
  setup() {
    const state = reactive({
      table: {
        //检索
        search: {
          state: false,
          vm: {
            projectId: "",
          },
        },
        loading: false,
        /* pageSizeOptions: ["10", "20", "30", "40", "50", "100", "500"],
        rows: 10,
        page: 1,
        total: 0, */
        selectedRowKeys: [],
        data: [],
      },
      form: {
        visible: false,
        revisible: false,
        key: Object,
      },
      columns: [
        {
          title: "项目名称",
          dataIndex: "projectName",
          key: "projectName",
          width: 200,
          ellipsis: true,
        },
        {
          title: "作业名称",
          dataIndex: "name",
          key: "name",
          width: 200,
          ellipsis: true,
        },
        {
          title: "分组",
          dataIndex: "groupName",
          key: "groupName",
          width: 120,
        },
        {
          title: "最后执行时间",
          dataIndex: "executeTime",
          key: "executeTime",
          width: 200,
          slots: {
            customRender: "time",
          },
        },
        {
          title: "间隔",
          dataIndex: "cron",
          key: "cron",
          width: 120,
        },
        {
          title: "状态",
          dataIndex: "state",
          key: "state",
          width: 100,
          slots: {
            customRender: "state",
          },
        },
        {
          title: "请求方式",
          dataIndex: "requsetMode",
          key: "requsetMode",
          width: 100,
          slots: {
            customRender: "requsetMode",
          },
        },
        {
          title: "apiUrl",
          dataIndex: "apiUrl",
          key: "apiUrl",
          width: 300,
          ellipsis: true,
        },
        {
          title: "描述",
          dataIndex: "remark",
          key: "remark",
          width: 300,
          ellipsis: true,
        },
        {
          title: "操作",
          key: "action",
          width: 100,
          slots: {
            customRender: "action",
          },
        },
      ],
      dataSource: [],
      projectSource: [],
      stateBool: true,
      timer: undefined,
      visible: false,
    });

    ///CheCkbox触发事件
    const methods = {
      onSelectChange(selectedRowKeys) {
        state.table.selectedRowKeys = selectedRowKeys;
      },
      //警告提示
      warning() {
        this.$message.warning("你还没有选中任务");
      },
      //选着错误类型
      error() {
        this.$message.error("不合理的非法请求");
      },
      //重置检索条件
      /* onResetSearch() {
        let searchVm = state.table.search.vm;
        for (let key in searchVm) {
          searchVm[key] = "";
        }
        methods.findList();
      }, */
      findProjectList() {
        state.loading = true;
        service
          .findList("Project")
          .finally(() => {
            state.loading = false;
          })
          .then((res) => {
            state.projectSource = res.data;
          });
      },
      //获取列表数据
      findList() {
        state.table.loading = true;
        service.findList("Tasks", state.table.search.vm.projectId).then((res) => {
          state.dataSource = res.data;
          state.table.loading = false;
        });
      },
      //删除数据
      deleteList(id) {
        tools.confirm("确定删除", function () {
          service.deleteList("Tasks", id).then((res) => {
            if (res.code != 1) return;
            tools.message("删除成功!", "成功");
            methods.findList();
          });
        });
      },
      run() {
        let ids = state.table.selectedRowKeys;
        //判断是否有选中ID
        if (ids.length == 0) {
          return tools.message("请选择要操作的数据！");
        }
        let flag = false;
        for (let i = 0; i < ids.length; i++) {
          let item = ids[i];
          let row = state.dataSource.filter((w) => w.id == item)[0];
          if (row.state == 1) {
            flag = true;
            break;
          }
        }
        if (flag) {
          return tools.message("请不要操作已启动任务！");
        }
        tools.confirm("确定启动", function () {
          service.run("Tasks", ids).then((res) => {
            if (res.code != 1) return;
            tools.message("运行成功!", "成功");
            methods.findList();
          });
        });
      },
      close() {
        let ids = state.table.selectedRowKeys;
        //判断是否有选中ID
        if (ids.length == 0) {
          return tools.message("请选择要操作的数据！");
        }
        let flag = false;
        for (let i = 0; i < ids.length; i++) {
          let item = ids[i];
          let row = state.dataSource.filter((w) => w.id == item)[0];
          if (row.state == 0) {
            flag = true;
            break;
          }
        }
        if (flag) {
          return tools.message("请不要操作已关闭任务！");
        }
        tools.confirm("确定关闭", function () {
          service.close("Tasks", ids).then((res) => {
            if (res.code != 1) return;
            tools.message("关闭成功!", "成功");
            methods.findList();
          });
        });
      },
      //打开表单页面
      openForm(id) {
        state.form.visible = true;
        state.form.key = id;
        console.log("表单的ID", state.form.key);
      },
      openRecord(id) {
        state.form.revisible = true;
        state.form.key = id;
      },
      timeFormat(time) {
        return moment(time).format("YYYY-MM-DD HH:mm:ss");
      },
      saveChange() {
        state.form.visible = false;
        methods.findList();
      },
    };
    const handleChange = (value) => {
      state.table.search.vm.projectId = value;
      methods.findList();
    };
    const filterOption = (input, option) => {
      return option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    };
    onMounted(() => {
      methods.findList();
      methods.findProjectList();
      state.timer = setInterval(() => {
        methods.findList();
      }, 60 * 1000);
    });
    onBeforeUnmount(() => {
      clearInterval(state.timer);
    });
    return {
      filterOption,
      handleChange,
      ...methods,
      ...toRefs(state),
    };
  },
});
</script>
<style scoped>
.ant-table-striped :deep(.table-striped) {
  background-color: #fafafa;
}
.ant-spin-nested-loading {
  min-height: 600px;
}
</style>
